<?php

namespace app\admin\controller;

use app\admin\service\CourseService;
use app\models\CampusModel;
use app\models\CampusPriceConfigureModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\GoodsWaitModel;
use app\models\ScheduleModel;

/**
 * Class Course.
 */
class Course extends Common
{
    /**
     * CampusPriceConfigureModel 校区配置模型.
     *
     * @var CampusPriceConfigureModel
     */
    protected $campusPriceConfigureModel;

    /**
     * CampusModel 校区模型.
     *
     * @var CampusModel
     */
    protected $campusModel;

    /**
     * ScheduleModel 上课进度模型.
     *
     * @var ScheduleModel
     */
    protected $scheduleModel;

    /**
     * CourseModel 课程模型.
     *
     * @var CourseModel
     */
    protected $courseModel;

    /**
     * 课程管理.
     *
     * @throws \think\Exception
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function lists()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $course = $this->courseModel->getCourseManageLists($param);

            $this->success('success', '', $course, 0);
        }

        return $this->fetch();
    }

    /**
     * 添加课程.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $data['price'] = $data['price'] * 100;
            if($data['cost_type'] == 97){
                $data['unit'] = '期';
            }elseif ($data['cost_type'] == 95){
                $data['unit'] = '小时';
                $data['class_num'] = 1;
                $data['class_time'] = 60;
            }elseif ($data['cost_type'] == 89){
                $data['unit'] = '课次';
                $data['class_num'] = 1;
            }
            $data['total_price'] = $data['price'] *  $data['class_num'];
			$res = $this->courseModel->save($data);
			$course['id'] = $this->courseModel->id;
			$course['course_name'] = $this->courseModel->course_name;
			if (false !== $res) {
				$this->success('添加成功', '', $course, 1);
			}
			$this->error('添加课程失败', null, '', 1);

        }
		$campus_where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$campus_where['id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$campus_where['id'] = ['in',get_current_campus_id()];
		}
		$campus_where['status'] = 1;
		$campus = $this->campusModel->where($campus_where)->select()->toArray();
        $this->dictionary();
        return $this->fetch('', [
            'year' => date('Y'),
			'campus' => $campus
        ]);
    }

	/**
	 * 编辑课程.
	 *
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function edit()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			$data['price'] = $data['price'] * 100;
			$data['total_price'] = $data['price'] *  $data['class_num'];
			if($data['cost_type'] == 97){
				$data['unit'] = '期';
			}elseif ($data['cost_type'] == 95){
				$data['unit'] = '小时';
				$data['class_time'] = 60;
			}elseif ($data['cost_type'] == 89){
				$data['unit'] = '课次';
			}
			if ($data['id']) {
				$res = $this->courseModel->save($data, ['id' => $data['id']]);
				$course['id'] = $this->courseModel->id;
				$course['course_name'] = $this->courseModel->course_name;
				if (false !== $res) {
					$this->success('更新成功', '', $course, 1);
				}
				$this->error('更新课程失败', null, '', 1);
			}
		}
		$campus = $this->campusModel->where(['id'=>input('campus_id'),'status'=>1])->select()->toArray();
		$this->dictionary();
		$course = [];
		if (input('id')) {
			$course = $this->courseModel->get(input('id'));
			$course['price'] = $course['price'] / 100;
		}

		return $this->fetch('', [
		    'course_id' => input('id'),
		    'campus_id' => input('campus_id'),
			'year' => date('Y'),
			'course' => $course,
			'campus' => $campus
		]);
	}

    /**
     * 校区配置.
     * @throws \think\exception\DbException
     */
    public function addCampus()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $ids = input('ids');
            $str_ids = explode(',', $ids);
            $data['course_id'] = input('course_id');
            $price = $this->courseModel->get($data['course_id'])['price'];
            $res = [];
            foreach ($str_ids as $id) {
                $data['campus_id'] = $id;
                $campusPriceConfigure = $this->campusPriceConfigureModel->get(['course_id'=>$data['course_id'],'campus_id'=>$id]);
                dd($campusPriceConfigure);
                if($campusPriceConfigure){
                    $res = $this->campusPriceConfigureModel->save(['course_id'=>$data['course_id'],'campus_id'=>$id],['price'=>$campusPriceConfigure['price']]);
                }else{
                    $data['price'] = $price;
                    $res = CampusPriceConfigureModel::create($data);
                }
            }
            if (false !== $res) {
                $this->success('添加成功', '', '', 1);
            }
            $this->error('添加失败', null, '', 1);
        }
    }

    /**
     * 校区授权.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function authorization()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = $this->campusModel->getCampusLists($param);

            $this->success('success', '', $campus, 0);
        }
        $price = $this->courseModel->get(input('id'))['price'];

        return $this->fetch('', [
            'course_id' => input('id'),
            'course_name' => input('course_name'),
            'price' => $price,
        ]);
    }

    /**
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function campus_price_configure()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $campusPriceConfigure = $this->campusPriceConfigureModel->get(['course_id' => $data['course_id'], 'campus_id' => $data['campus_id']]);
            if ($campusPriceConfigure) {
                $res = $this->campusPriceConfigureModel->save($data, ['course_id' => $data['course_id'], 'campus_id' => $data['campus_id']]);
            } else {
                $res = $this->campusPriceConfigureModel->save($data);
            }
            $course_id = $this->campusPriceConfigureModel->course_id;
            if (!$res) {
                $this->error('添加失败', null, '', 1);
            }
            $this->success('添加成功', '', $course_id, 1);
        }

        return $this->fetch();
    }

    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return \think\response\Json|\think\response\View
     */
    public function add_goods()
    {
        if (request()->isPost()) {
            return json((new CourseService())->add_goods());
        }
        $this->dictionary();
        $goodsWaitModel = new GoodsWaitModel();
        $count = $goodsWaitModel->count();
        $this->assign('count', $count);

        return view();
    }

    public function goods_wait()
    {
        if (request()->isPost()) {
            return json((new CourseService())->goodsWait());
        }

        return view();
    }

    public function goods_wait_del()
    {
        if (request()->isPost()) {
            return json((new CourseService())->goodsWaitDel());
        }
    }

    /**
     * 删除课程.
     *
     * @return mixed
     */
    public function del()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $ids = input('ids');
            $where['id'] = ['in', $ids];
            if (!$this->courseModel->where($where)->delete()) {
                $this->error('删除失败', null, '', 1);
            }
            $this->success('删除成功', '', '', 1);
        }
    }

    /**
     * 改变分类状态
     *
     * @return \think\response\Json
     */
    public function course_check_status()
    {
        if (request()->isPost()) {
            return json((new CourseService())->course_check_status());
        }
    }

    /**
     * 实例化.
     *
     * @return bool|void
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->campusPriceConfigureModel = new CampusPriceConfigureModel();
        $this->courseModel = new CourseModel();
        $this->campusModel = new CampusModel();
        $this->scheduleModel = new ScheduleModel();
    }
}
